package cn.b.sky.mes.cm.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import cn.b.sky.mes.cm.dao.WorkDayTypeDao;
import cn.b.sky.mes.cm.model.WorkDayPeriod;
import cn.b.sky.mes.cm.model.WorkDayType;
import cn.b.sky.mes.cm.model.condition.WorkDayTypeCondition;
import cn.b.sky.mes.cm.service.WorkDayTypeService;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.common.utils.DateUtils;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;

/**
 * 
 * <strong>Title : WorkDayTypeServiceImpl.java<br>
 * </strong> <strong>Package : cn.b.sky.mes.cm.service.impl<br>
 * </strong> <strong>Description : </strong>工作日类型业务实现类<br>
 * <strong>Create on : 2016-1-8 下午02:01:35<br>
 * </strong>
 * <p>
 * 
 * @author zhaoxin01<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 *          <strong>修改历史:</strong><br>
 *          修改人 | 修改日期 | 修改描述<br>
 *          -------------------------------------------<br>
 * <br>
 * <br>
 */
@Service("workDayTypeService")
public class WorkDayTypeServiceImpl implements WorkDayTypeService {

  private static final Logger LOGGER = LoggerFactory.getLogger(WorkDayTypeServiceImpl.class);

  @Resource
  WorkDayTypeDao workDayTypeDao;

  @Override
  public List<WorkDayType> selectWorkDayTypeByCondition(WorkDayTypeCondition workDayTypeCondition) {
    return workDayTypeDao.selectWorkDayTypeByCondition(workDayTypeCondition);
  }

  @Override
  public int selectWorkDayTypeCount(WorkDayTypeCondition workDayTypeCondition) {
    return workDayTypeDao.selectWorkDayTypeCount(workDayTypeCondition);
  }

  @Override
  public WorkDayType selectWorkDayType(String siteCode, String dayTypeCode) {
    return workDayTypeDao.selectWorkDayType(siteCode, dayTypeCode);
  }

  @Override
  public void insertWorkDayType(WorkDayType workDayType) {
    workDayTypeDao.insertWorkDayType(workDayType);
    if (workDayType.getPeriods() != null) {
      List<WorkDayPeriod> pers = workDayType.getPeriods();
      Collections.sort(pers);
      long i = 1;
      if (pers.size() > 0) {
        DateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd");
        String tody = dfDate.format(new Date());
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String start = pers.get(0).getStartTime();
        String end = pers.get(pers.size() - 1).getEndTime();
        start = tody + " " + start;
        end = tody + " " + end;
        Date startTime = null;
        Date endTime = null;
        if (pers.get(0).getNextDayFlag() != 1
            && (pers.get(pers.size() - 1).getSpanDaysFlag() == 1 || pers.get(pers.size() - 1).getNextDayFlag() == 1)) {
          try {
            startTime = df.parse(start);
            endTime = DateUtils.getDateUtils().operationDay(df.parse(end), 1);
          } catch (ParseException e) {
            LOGGER.error("{}", e);
          }
        } else {
          try {
            startTime = df.parse(start);
            endTime = df.parse(end);
          } catch (ParseException e) {
            LOGGER.error("{}", e);
          }
        }
        long diff = endTime.getTime() - startTime.getTime();
        if (diff > 24 * 60 * 60 * 1000) {
          throw ImeException.newException("workPeriodOver.M");
        }
      }
      for (WorkDayPeriod p : pers) {
        p.setSiteCode(workDayType.getSiteCode());
        p.setDayTypeCode(workDayType.getDayTypeCode());
        p.setOrdinal(i++);
        workDayTypeDao.insertWorkDayPeriod(p);
      }
    }

  }

  @Override
  public void updateWorkDayType(WorkDayType workDayType) {
    workDayTypeDao.updateWorkDayType(workDayType);
    workDayTypeDao.deleteWorkDayPeriod(workDayType.getSiteCode(), workDayType.getDayTypeCode());
    if (workDayType.getPeriods() != null) {
      List<WorkDayPeriod> pers = workDayType.getPeriods();
      Collections.sort(pers);
      long i = 1;
      if (pers.size() > 0) {
        DateFormat dfDate = new SimpleDateFormat("yyyy-MM-dd");
        String tody = dfDate.format(new Date());
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String start = pers.get(0).getStartTime();
        String end = pers.get(pers.size() - 1).getEndTime();
        start = tody + " " + start;
        end = tody + " " + end;
        Date startTime = null;
        Date endTime = null;
        if (pers.get(0).getNextDayFlag() != 1
            && (pers.get(pers.size() - 1).getSpanDaysFlag() == 1 || pers.get(pers.size() - 1).getNextDayFlag() == 1)) {
          try {
            startTime = df.parse(start);
            endTime = DateUtils.getDateUtils().operationDay(df.parse(end), 1);
          } catch (ParseException e) {
            LOGGER.error("{}", e);
          }
        } else {
          try {
            startTime = df.parse(start);
            endTime = df.parse(end);
          } catch (ParseException e) {
            LOGGER.error("{}", e);
          }
        }
        long diff = endTime.getTime() - startTime.getTime();
        if (diff > 24 * 60 * 60 * 1000) {
          throw ImeException.newException("workPeriodOver.M");
        }

      }
      for (WorkDayPeriod p : pers) {
        p.setSiteCode(workDayType.getSiteCode());
        p.setDayTypeCode(workDayType.getDayTypeCode());
        p.setOrdinal(i++);
        workDayTypeDao.insertWorkDayPeriod(p);
      }
    }

  }

  @Override
  public List<WorkDayPeriod> selectWorkDayPeriodByWorkDay(String siteCode, String dayTypeCode) {
    return workDayTypeDao.selectWorkDayPeriodByWorkDay(siteCode, dayTypeCode);
  }

  @Override
  public BatchJobReport deleteWorkDayType(String siteCode, String dayTypeCode) {
    String cause = "";
    Boolean success = true;
    try {
      workDayTypeDao.deleteWorkDayPeriod(siteCode, dayTypeCode);
      workDayTypeDao.deleteWorkDayType(siteCode, dayTypeCode);
    } catch (Exception e) {
      LOGGER.error("{}", e);
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),SecurityContextUtil.getLanguageCode(),
            "dataBaseOperationPkFail.M")
            + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),SecurityContextUtil.getLanguageCode(), "notDelete.M");
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(dayTypeCode, cause, success, SecurityContextUtil.getLanguageCode(),SecurityContextUtil.getSiteCode());
  }

  @Override
  public List<WorkDayType> selectUnLockWorkDayTypeList(String siteCode) {
    return workDayTypeDao.selectUnLockWorkDayTypeList(siteCode);
  }

  @Override
  public List<WorkDayPeriod> selectWorkDayPeriods(String siteCode) {
    return workDayTypeDao.selectWorkDayPeriods(siteCode);
  }

  @Override
  public List<WorkDayPeriod> selectWorkDayPeriodsByWorkcenterAndDate(String siteCode, String workcenterCode, String date) {
    //  Auto-generated method stub
    return workDayTypeDao.selectWorkDayPeriodsByWorkcenterAndDate(siteCode, workcenterCode, date);
  }

}
